/*********************************************************************************
 *      Copyright:  (C) 2023 iot<iot@email.com>
 *                  All rights reserved.
 *
 *       Filename:  data_process.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(04/20/23)
 *         Author:  iot <iot@email.com>
 *      ChangeLog:  1, Release initial version on "04/20/23 19:51:59"
 *                 
 ********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stddef.h>
#include <time.h>
#include <sys/types.h>
#include <dirent.h>
#include<fcntl.h>
#include <unistd.h>

#include "get_data.h"
#include "data_process.h"
#include "logger.h"
int sample_package(sample_data_t *sample_data)
{
        if( !sample_data  )
        {
                printf("invalid input arguments\n");
                return -1;
        }

        get_devid(sample_data->devid,sizeof(sample_data->devid));
        get_time(sample_data->time,sizeof(sample_data->time));
        ds18b20_get_temperature(&sample_data->temp);
        
        return 0;
        
        //log_info("%s",sample_data->devid);
        //log_info("%s",sample_data->time);
        //log_info("%5.3f",sample_data->temp);

        //snprintf(buf,size,"%s|%s|%5.3f",sample_data->devid,sample_data->time,sample_data->temp);
		//return strlen(buf);

}

int send_package(socket_t socket,sample_data_t sample_data)
{
	int             rv = 0;
    int             i = 0;
    int             left_bytes;
	char			buf[128];

	if( !socket  )
    {
		log_warning("invalid input arguments\n");
        return -1;
	}
	
	snprintf(buf,sizeof(buf),"%s|%s|%5.3f",sample_data.devid,sample_data.time,sample_data.temp);
	left_bytes = strlen(buf);
	
	while( left_bytes > 0 )
	{
		if((rv=write(socket.sockfd,&buf[i],left_bytes))<0)
        {
			log_info("socket[%d] write() failure:%s,close socket now\n",socket.sockfd,strerror(errno));         //socket_term(sock);
            close(socket.sockfd);
            return -2;
		}
		else if( rv == left_bytes )
        {
			log_info("socket send %d bytes data over\n",left_bytes);
            return 0;
		}
		else
        {
			/* not send over this time, continue send left data*/
			i = i+rv;
			left_bytes = rv;
			continue;
		}
	}
}
